package com.android.sunflower.ui.plantlist

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SearchView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.sunflower.R
import com.android.sunflower.databinding.FragmentPlantListBinding
import com.android.sunflower.logic.room.entities.Flower
import com.android.sunflower.ui.MainActivity

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [PlantListFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class PlantListFragment : Fragment() {

    private var _plantListBinding:FragmentPlantListBinding?=null

    private val plantListBinding get() = _plantListBinding


    @SuppressLint("HandlerLeak")
    inner class MyHandler:Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if(msg.what==querySuccess){
                plantListBinding?.plantMenuList?.adapter?.notifyDataSetChanged()
            }
        }
    }
    companion object{
        const val querySuccess=888
        var handler:MyHandler?=null
        var viewModel:PlantListViewModel?=null
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        handler=MyHandler()
        //这个ViewModel应该和MainActivity的生命周期绑定，不然每次都要重新查询
        //不可行，如果和MainActivity生命周期绑定的话，每次切换黑暗模式就会产生Bug，可能因为黑暗模式下重建了Activity
        viewModel= ViewModelProvider(this).get(PlantListViewModel::class.java)
        //如果viewModel中没有数据，则查询数据库获取数据。
        if(viewModel?.plantList?.isEmpty()!!){
            viewModel?.selectAll()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _plantListBinding=FragmentPlantListBinding.inflate(inflater,container,false)
        if(viewModel?.queryText!=""){
            plantListBinding?.plantListSearchView?.visibility=View.VISIBLE
        }
        return plantListBinding?.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        plantListBinding?.myGardenToolbar?.setNavigationOnClickListener {
            activity?.onBackPressed()
        }
        //点击搜索图标时展开搜索栏
        plantListBinding?.myGardenToolbar?.setOnMenuItemClickListener {item->
            if(item.itemId==R.id.searchButton){
                plantListBinding?.plantListSearchView?.visibility=View.VISIBLE
            }
            true
        }
        //点击关闭图标时关闭搜索栏并恢复数据
        plantListBinding?.plantListSearchView?.setOnCloseListener {
            plantListBinding?.plantListSearchView?.visibility=View.GONE
            viewModel?.searchCanceled()
            viewModel?.queryText=""
            plantListBinding?.plantMenuList?.adapter?.notifyDataSetChanged()
            true
        }
        //搜索相关逻辑
        plantListBinding?.plantListSearchView?.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                val name=query!!
                viewModel?.searchByName(name)
                viewModel?.queryText=name
                plantListBinding?.plantMenuList?.adapter?.notifyDataSetChanged()
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                return true
            }
        })
        plantListBinding?.plantMenuList?.setHasFixedSize(true)
        plantListBinding?.plantMenuList?.adapter=PlantListAdapter(viewModel?.plantList!!)
        plantListBinding?.plantMenuList?.layoutManager=LinearLayoutManager(MainActivity.runningInstance)
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _plantListBinding=null
    }

    override fun onDestroy() {
        super.onDestroy()
        handler=null
    }
}